package com.lix.config;

import com.alibaba.fastjson.JSONObject;
import com.lix.constant.CommonContent;
import com.lix.mapper.SystemInnerConfigRepository;
import com.lix.pojo.inner.SystemInnerDTO;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 系统内部配置，初始化系统内部的配置数据
 */
@Data
@Configuration
public class SystemInnerConfig {

    // 从库里读取配置
    @Autowired
    private SystemInnerConfigRepository innerConfigRepository;

    // 不可被删除的用户及角色
    private List<String> innerUserList = new ArrayList<>(0);
    private List<String> innerSuperAdminList = new ArrayList<>(0);
    private List<Integer> innerRoleList = new ArrayList<>(0);
    private List<Integer> innerMenuList = new ArrayList<>(0);
    private Integer superAdminRoleId;
    private String superAdminRoleName;
    private Integer adminRoleId;
    private String adminRoleName;
    private Integer userRoleId;
    private String userRoleName;

    /**
     * 在 Spring 容器初始化完成后被调用
     */
    @PostConstruct
    public void initMethod(){
        reloadConfig();
    }

    public synchronized void reloadConfig() {
        List<Map<String, String>> list = innerConfigRepository.querySysInner(CommonContent.SYS_INNER);
        Map<String, String> dictMap = new HashMap<>();

        for (Map<String, String> result : list) {
            dictMap.put(result.get("dict_key"), result.get("dict_value"));
        }

        SystemInnerDTO dto = SystemInnerDTO.fromMap(dictMap);

        String innerUser = dto.getInnerUser();
        String innerSuperAdmin = dto.getInnerSuperAdmin();
        String innerRole = dto.getInnerRole();
        String innerMenu = dto.getInnerMenu();
        this.superAdminRoleId = dto.getSuperAdminRoleId();
        this.adminRoleId = dto.getAdminRoleId();
        this.superAdminRoleName = dto.getSuperAdminRoleName();
        this.adminRoleName = dto.getAdminRoleName();
        this.userRoleId = dto.getUserRoleId();
        this.userRoleName = dto.getUserRoleName();

        if (StringUtils.hasLength(innerUser)) {
            this.innerUserList = Arrays.asList(innerUser.split(","));
        }

        if (StringUtils.hasLength(innerSuperAdmin)) {
            this.innerSuperAdminList = Arrays.asList(innerSuperAdmin.split(","));
        }

        if (StringUtils.hasLength(innerRole)) {
            this.innerRoleList = Arrays.stream(innerRole.split(",")).map(Integer::parseInt).collect(Collectors.toList());
        }

        if (StringUtils.hasLength(innerMenu)) {
            this.innerMenuList = Arrays.stream(innerMenu.split(",")).map(Integer::parseInt).collect(Collectors.toList());
        }
    }
}
